// utils/scanner.js

const request = require('./request');

module.exports = {
  // 扫描小程序码
  async scanCode() {
    try {
      const res = await wx.scanCode({
        scanType: ['qrCode'],
        onlyFromCamera: true
      });
      
      // 解析参数
      const params = {};
      const query = res.path.split('?')[1];
      if (query) {
        query.split('&').forEach(item => {
          const [key, value] = item.split('=');
          params[key] = decodeURIComponent(value);
        });
      }

      return params;
    } catch (err) {
      if (err.errMsg.includes('cancel')) {
        throw new Error('用户取消扫码');
      }
      throw new Error('扫码失败');
    }
  },

  // 获取扫码场景信息
  async getSceneInfo(sceneId) {
    try {
      const res = await request.get('/api/scan/scene', {
        sceneId
      });
      return res.data;
    } catch (err) {
      throw err;
    }
  },

  // 授权登录
  async authorizeLogin(sceneId, accountId) {
    try {
      const res = await request.post('/api/scan/authorize', {
        sceneId,
        accountId
      });
      return res.data;
    } catch (err) {
      throw err;
    }
  },

  // 取消授权
  async cancelAuthorization(sceneId) {
    try {
      const res = await request.post('/api/scan/cancel', {
        sceneId
      });
      return res.data;
    } catch (err) {
      throw err;
    }
  }
};
